
import axios from "axios"
import {message} from "antd"
import {history} from "../utils"

let hide =null;

export function showLoading(){
    hide = message.loading("请求中...")
}

export function showSuccess(msg){
    hide&&hide();
    msg = msg || "请求成功"
    message.success(msg)
}

export function showFail(msg){
    hide&&hide();
    msg = msg || "未知错误"
    message.error(msg);
}

const baseURL="http://localhost:2008" 
axios.defaults.baseURL = baseURL;

axios.interceptors.request.use(function(config){
    //成功
    // showLoading()
    config.headers['token'] = localStorage.getItem('token')
    return config
},function(err){
    showFail('网络异常')
    return Promise.reject(err);
})

axios.interceptors.response.use(function(response){
    //成功
    if(response.data.code==200){
        // showSuccess(response.data.msg)
    }

    if(response.data.code==402 || response.data.code==500){
        // error 
        showFail(response.data.msg)
    }

    if(response.data.code==3000){
        showFail(response.data.msg)
        history.push("/login")
        localStorage.removeItem('token');
        localStorage.removeItem('username');
    }
    return response;
},function(err){
    //失败
    showFail('服务器异常')
    return Promise.reject(err);
})

//GET  请求
export const get =function(url,params,headers){
    return new Promise(function(resolve,reject){
        axios.get(url,{
            params,
            headers
        }).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}


//post 请求
export const post=function(url,body,params,headers){
    return new Promise (function(resolve,reject){
        axios.post(url,body,{
            params,
            headers,
        }).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

export {axios,baseURL}